package com.tf.six.service.impl;

import com.tf.six.entity.User;
import com.tf.six.mapper.UserMapper;
import com.tf.six.service.TransactionStatisticService;
import com.tf.six.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TransactionStatisticServiceImpl implements TransactionStatisticService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final UserMapper userMapper;

    @Autowired
    public TransactionStatisticServiceImpl(RedisTemplate<String, Object> redisTemplate,
                                           UserMapper userMapper) {
        this.redisTemplate = redisTemplate;
        this.userMapper = userMapper;
    }

    @Override
    public List<Map<String, Object>> getUserTransactionAmountRank(int limit) {
        // 从Redis获取用户交易金额排行
        Set<ZSetOperations.TypedTuple<Object>> users = redisTemplate.opsForZSet()
                .reverseRangeWithScores(RedisKeyUtil.ACTIVE_USER_KEY, 0, limit - 1);

        if (users == null || users.isEmpty()) {
            return Collections.emptyList();
        }

        return users.stream()
                .map(tuple -> {
                    Long userId = Long.valueOf(tuple.getValue().toString());
                    User user = userMapper.selectById(userId);
                    if (user == null) {
                        return null;
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("user", user);
                    map.put("totalAmount", tuple.getScore());
                    return map;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    @Override
    public List<Map<String, Object>> getUserTransactionCountRank(int limit) {
        // 这里简单实现，实际项目中可能需要单独维护一个交易次数的ZSET
        // 或者使用Hash结构存储用户的交易次数和交易金额

        // 这里我们复用ACTIVE_USER_KEY，实际项目中应该分开
        return getUserTransactionAmountRank(limit);
    }

    @Override
    public void incrementUserTransactionStat(Long userId, Double amount) {
        // 增加用户交易金额统计
        redisTemplate.opsForZSet().incrementScore(
                RedisKeyUtil.ACTIVE_USER_KEY,
                userId.toString(),
                amount
        );
    }
}